package com.sk.leetcode.arithmetic.test1_10;

import java.util.HashMap;
import java.util.Map;

/**
 * 给定一个字符串，找出不含有重复字符的最长子串的长度。
 */
public class Test3 {

    public static void main(String[] args) {
        int n = lengthOfLongestSubstring2("bbtabludsadawdasdasdasdasbbnhgrtyuio");
        System.out.println(n);
    }

    public static int lengthOfLongestSubstring(String s) {
        if(s != null && s.length() != 0) {
            String[] strs = s.split("");
            Map<String, Integer> map = new HashMap<>();
            int n = 0, m = 0, max = 0;
            for (int i = 0; i < strs.length; i++) {
                String str = strs[i];
                if(map.get(str) != null) {
                    if(m > max) {
                        max = m;
                    }
                    int p = map.get(str);
                    while (p > n) {
                        map.remove(strs[n++]);
                        m--;
                    }
                    n++;
                    map.put(str, i);
                } else {
                    map.put(str, i);
                    m++;
                }
            }
            if(m > max) {
                return m;
            }
            return max;
        }
        return 0;
    }


    public static int lengthOfLongestSubstring2(String s) {
        char[] chars = s.toCharArray();

        int indexStart = 0, maxLength = 0;
        for (int i = 1; i < chars.length; i++) {
            for (int j = indexStart; j < i; j++) {
                if (chars[i] == chars[j]) {
                    maxLength = Math.max(maxLength, i - indexStart);
                    indexStart = j + 1;
                    break;
                }
            }

        }
        return Math.max(maxLength, chars.length - indexStart);
    }
}
